<template>
  <div>
    <!-- 主内容区域 -->
    <div class="main-content">
      <div class="page-title">关键词推荐</div>

      <!-- 关键词推荐 -->
      <div class="keyword-suggestion">
        <div class="suggestion-header">
          <div class="suggestion-title">关键词推荐</div>
          <div class="suggestion-tabs">
            <div
              class="suggestion-tab"
              :class="{ 'active': suggestionType === 'related' }"
              @click="setSuggestionType('related')"
            >相关推荐</div>
            <div
              class="suggestion-tab"
              :class="{ 'active': suggestionType === 'longtail' }"
              @click="setSuggestionType('longtail')"
            >长尾词</div>
            <div
              class="suggestion-tab"
              :class="{ 'active': suggestionType === 'trending' }"
              @click="setSuggestionType('trending')"
            >上升词</div>
          </div>
        </div>

        <div class="keyword-input">
          <el-input
            v-model="keyword"
            placeholder="输入关键词，例如：夏季穿搭"
            suffix-icon="el-icon-search"
            @keyup.enter="searchKeywords"
          ></el-input>
          <el-button type="primary" @click="searchKeywords">搜索</el-button>
        </div>

        <div v-if="keywordHistory.length > 0" class="keyword-history">
          <div class="text-gray-500">搜索历史：</div>
          <div
            class="history-tag"
            v-for="(item, index) in keywordHistory"
            :key="index"
            @click="fillKeyword(item)"
          >
            <span>{{ item }}</span>
            <i
              class="fa-solid fa-times-circle"
              @click.stop="removeHistory(index)"
            ></i>
          </div>
          <div class="history-tag" @click="clearHistory">
            <i class="fa-solid fa-trash"></i>
            <span>清空历史</span>
          </div>
        </div>

        <div v-if="suggestions.length > 0" class="suggestion-results">
          <div class="results-header">
            <div class="results-count">找到 {{ suggestions.length }} 个关键词</div>
            <div class="results-sort">
              <div class="sort-label">排序：</div>
              <el-radio-group v-model="sortType">
                <el-radio-button label="relevance">相关性</el-radio-button>
                <el-radio-button label="search_volume">搜索量</el-radio-button>
                <el-radio-button label="competition">竞争度</el-radio-button>
              </el-radio-group>
            </div>
          </div>

          <div class="suggestion-grid">
            <div
              class="suggestion-card"
              v-for="(item, index) in sortedSuggestions"
              :key="index"
            >
              <div class="card-header">
                <div class="keyword-text">{{ item.text }}</div>
                <div class="keyword-score">{{ item.score.toFixed(1) }}</div>
              </div>

              <div class="keyword-metrics">
                <div>
                  <i class="fa-solid fa-eye"></i>
                  {{ item.views | numberFormat }}
                </div>
                <div>
                  <i class="fa-solid fa-arrow-up text-green-500"></i>
                  {{ item.growthRate }}%
                </div>
                <div>
                  <i class="fa-solid fa-chart-line"></i>
                  {{ item.competition }}
                </div>
              </div>

              <div class="keyword-actions">
                <el-button type="text" size="small" @click="copyKeyword(item.text)">复制</el-button>
                <el-button type="text" size="small" @click="addToList(item.text)">加入列表</el-button>
                <el-button type="text" size="small" @click="analyzeKeyword(item.text)">分析</el-button>
              </div>
            </div>
          </div>

          <div class="mt-6 text-center">
            <el-button type="text" @click="loadMore">加载更多</el-button>
          </div>
        </div>

        <div
          v-else-if="keyword && suggestions.length === 0"
          class="empty-results text-center py-10"
        >
          <i class="fa-solid fa-search text-gray-400 text-4xl mb-4"></i>
          <p class="text-gray-500">没有找到与"{{ keyword }}"相关的关键词</p>
          <el-button type="primary" size="small" @click="keyword = ''">重新搜索</el-button>
        </div>
      </div>

      <!-- 关键词分析图表 -->
      <div v-if="showChart" class="keyword-chart">
        <div class="trend-header">
          <div class="trend-title">{{ currentAnalysisKeyword }} 趋势分析</div>
          <div class="chart-actions">
            <el-select v-model="chartTimeRange" placeholder="选择时间范围" size="small">
              <el-option label="近7天" value="7d"></el-option>
              <el-option label="近30天" value="30d"></el-option>
              <el-option label="近90天" value="90d"></el-option>
            </el-select>
          </div>
        </div>

        <div class="chart-container">
          <canvas id="keywordChart"></canvas>
        </div>
      </div>

      <!-- 相关推荐 -->
      <div v-if="showRelated" class="related-keywords">
        <div class="trend-title">相关推荐关键词</div>

        <div class="related-list">
          <div
            class="related-tag"
            v-for="tag in relatedTags"
            :key="tag"
            @click="fillKeyword(tag)"
          >{{ tag }}</div>
        </div>
      </div>
    </div>

    <!-- 关键词列表弹窗 -->
    <el-dialog v-model="keywordListVisible" title="关键词列表">
      <template #content>
        <div class="keyword-list-content">
          <div class="list-header">
            <el-input v-model="listSearch" placeholder="搜索关键词" size="small" style="width: 200px;"></el-input>
            <el-button type="primary" size="small" @click="exportKeywords">导出关键词</el-button>
          </div>

          <el-table :data="filteredKeywordList" stripe style="width: 100%">
            <el-table-column prop="text" label="关键词"></el-table-column>
            <el-table-column prop="views" label="搜索量" :formatter="formatNumber"></el-table-column>
            <el-table-column prop="growthRate" label="增长率"></el-table-column>
            <el-table-column prop="competition" label="竞争度"></el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button size="mini" type="text" @click="removeFromList(scope.row)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div v-if="keywordList.length === 0" class="empty-list text-center py-10">
            <i class="fa-solid fa-folder-open text-gray-400 text-4xl mb-4"></i>
            <p class="text-gray-500">关键词列表为空</p>
            <p class="text-gray-400 text-sm mt-2">从关键词推荐中选择关键词添加到列表</p>
          </div>
        </div>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="keywordListVisible = false">关闭</el-button>
          <el-button type="primary" @click="useSelectedKeywords">使用关键词</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import Chart from 'chart.js/auto';

export default {
  name: 'SuggestView',
  data() {
    return {
      activeMenu: 'keywords-suggest',
      keyword: '',
      suggestionType: 'related',
      sortType: 'relevance',
      keywordHistory: [],
      suggestions: [],
      keywordList: [],
      keywordListVisible: false,
      listSearch: '',
      showChart: false,
      currentAnalysisKeyword: '',
      chartTimeRange: '30d',
      showRelated: false,
      relatedTags: [],
      keywordChart: null
    };
  },
  computed: {
    sortedSuggestions() {
      if (this.sortType === 'relevance') {
        return [...this.suggestions].sort((a, b) => b.score - a.score);
      } else if (this.sortType === 'search_volume') {
        return [...this.suggestions].sort((a, b) => b.views - a.views);
      } else if (this.sortType === 'competition') {
        // 这里需要补充按竞争度排序的逻辑
        return this.suggestions;
      }
      return this.suggestions;
    },
    filteredKeywordList() {
      if (!this.listSearch) return this.keywordList;
      return this.keywordList.filter(item =>
        item.text.toLowerCase().includes(this.listSearch.toLowerCase())
      );
    }
  },
  filters: {
    numberFormat(value) {
      if (!value) return '0';

      if (value >= 10000) {
        return (value / 10000).toFixed(1) + 'w';
      }

      return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    }
  },
  methods: {
    handleOpen() {
      // 处理侧边栏菜单展开事件
    },
    handleClose() {
      // 处理侧边栏菜单关闭事件
    },
    setSuggestionType(type) {
      this.suggestionType = type;
      this.searchKeywords();
    },
    searchKeywords() {
      if (this.keyword.trim()) {
        if (!this.keywordHistory.includes(this.keyword)) {
          this.keywordHistory.unshift(this.keyword);
          if (this.keywordHistory.length > 10) {
            this.keywordHistory.pop();
          }
        }
        // 这里需要补充搜索关键词的逻辑
        // this.suggestions = ...
      }
    },
    fillKeyword(keyword) {
      this.keyword = keyword;
      this.searchKeywords();
    },
    removeHistory(index) {
      this.keywordHistory.splice(index, 1);
    },
    clearHistory() {
      this.keywordHistory = [];
    },
    copyKeyword(keyword) {
      navigator.clipboard.writeText(keyword).then(() => {
        this.$message.success('关键词已复制到剪贴板');
      });
    },
    addToList(keyword) {
      if (!this.keywordList.some(item => item.text === keyword)) {
        // 这里需要补充获取关键词详情的逻辑
        // 假设 item 包含 text, views, growthRate, competition 等属性
        const item = { text: keyword, views: 0, growthRate: 0, competition: 0 };
        this.keywordList.push(item);
        this.$message.success('关键词已加入列表');
      } else {
        this.$message.warning('关键词已存在于列表中');
      }
    },
    analyzeKeyword(keyword) {
      this.currentAnalysisKeyword = keyword;
      this.showChart = true;
      // 这里需要补充绘制图表的逻辑
      if (this.keywordChart) {
        this.keywordChart.destroy();
      }
      const ctx = document.getElementById('keywordChart').getContext('2d');
      this.keywordChart = new Chart(ctx, {
        type: 'line',
        data: {
          labels: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
          datasets: [{
            label: '搜索趋势',
            data: [12, 19, 3, 5, 2, 3, 10],
            borderColor: '#FE2C55',
            fill: false
          }]
        },
        options: {
          responsive: true
        }
      });
    },
    loadMore() {
      // 这里需要补充加载更多关键词的逻辑
    },
    exportKeywords() {
      // 这里需要补充导出关键词的逻辑
    },
    removeFromList(item) {
      const index = this.keywordList.indexOf(item);
      if (index > -1) {
        this.keywordList.splice(index, 1);
      }
    },
    useSelectedKeywords() {
      // 这里需要补充使用所选关键词的逻辑
      this.keywordListVisible = false;
    },
    formatNumber(row, column) {
      return this.$options.filters.numberFormat(row[column.property]);
    }
  },
  mounted() {
    // 组件挂载后可以初始化一些数据
  }
};
</script>

<style scoped lang="scss">

.page-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}

/* 关键词推荐相关样式 */
.keyword-suggestion {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
  margin-bottom: 20px;
}

.suggestion-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.suggestion-title {
  font-size: 18px;
  font-weight: 500;
}

.suggestion-tabs {
  display: flex;
  gap: 15px;
}

.suggestion-tab {
  padding: 8px 16px;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.suggestion-tab:hover {
  background-color: rgba(254, 44, 85, 0.1);
}

.suggestion-tab.active {
  background-color: var(--primary-color);
  color: white;
}

.keyword-input {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.keyword-input .el-input {
  flex: 1;
}

.keyword-history {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.history-tag {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 6px 12px;
  background-color: #F8F8F8;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.history-tag:hover {
  background-color: rgba(254, 44, 85, 0.1);
}

.suggestion-results {
  margin-top: 20px;
}

.results-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.results-count {
  color: var(--gray-color);
}

.results-sort {
  display: flex;
  align-items: center;
  gap: 10px;
}

.sort-label {
  color: var(--gray-color);
}

.suggestion-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}

.suggestion-card {
  padding: 16px;
  border-radius: 12px;
  border: 1px solid #EBEEF5;
  transition: all 0.3s ease;
  cursor: pointer;
}

.suggestion-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.keyword-text {
  font-size: 16px;
  font-weight: 500;
}

.keyword-score {
  background-color: rgba(254, 44, 85, 0.1);
  color: var(--primary-color);
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.keyword-metrics {
  display: flex;
  gap: 15px;
  color: var(--gray-color);
  font-size: 14px;
  margin-top: 10px;
}

.keyword-actions {
  display: flex;
  gap: 10px;
  margin-top: 16px;
}

/* 关键词分析图表 */
.keyword-chart {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
  margin-bottom: 20px;
}

.chart-container {
  height: 300px;
}

/* 相关推荐 */
.related-keywords {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.related-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.related-tag {
  padding: 8px 16px;
  background-color: #F8F8F8;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.related-tag:hover {
  background-color: rgba(254, 44, 85, 0.1);
  color: var(--primary-color);
}

</style>
